﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WorkFlowDemo.Flows;
using WorkflowFramework;

namespace WorkFlowDemo.Controllers
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    public class WorkFlowController : ControllerBase
    {
        private readonly ILogger<WorkFlowController> _logger;
        private readonly IWorkFlowBuilder _workFlowBuilder;
        private readonly MyWorkflow _myWorkflow;
        private readonly MyWorkflow2 _myWorkflow2;
        public WorkFlowController(ILogger<WorkFlowController> logger, MyWorkflow myWorkflow, MyWorkflow2 myWorkflow2, IWorkFlowBuilder workFlowBuilder)
        {
            _logger = logger;
            _myWorkflow = myWorkflow;
            _myWorkflow2 = myWorkflow2;
            _workFlowBuilder = workFlowBuilder;
        }
        [HttpGet]
        public async Task<bool> Health()
        {
            return true;
        }

        [HttpPost]
        public async Task<bool> Start()
        {
            if (_myWorkflow.IsRunning)
            {
                _logger.LogWarning("[{0}] 流程正在执行，请先停止", _myWorkflow.Name);
                return false;
            }
            _myWorkflow.Build(_workFlowBuilder);

            var task = Task.Run(async () =>
            {
                _logger.LogInformation("Start...");
                await _myWorkflow.Start();
                _logger.LogInformation("End...");
            });

            return true;
        }
        [HttpPost]
        public async Task<bool> Start2()
        {
            if (_myWorkflow2.IsRunning)
            {
                _logger.LogWarning("[{0}] 流程正在执行", _myWorkflow.Name);
                return false;
            }
            _myWorkflow2.Build(_workFlowBuilder);

            var task = Task.Run(async () =>
            {
                _logger.LogInformation("Start 2...");
                await _myWorkflow2.Start();
                _logger.LogInformation("End 2...");
            });

            return true;
        }

        [HttpPost]
        public async Task<bool> Continue()
        {
            _logger.LogInformation("Continue...");
            await _myWorkflow.Continue();
            return true;
        }
        [HttpPost]
        public async Task<bool> Pause()
        {
            _logger.LogInformation("Pause...");
            await _myWorkflow.Pause();
            return true;
        }
        [HttpPost]
        public async Task<bool> Retry()
        {
            _logger.LogInformation("Retry...");
            await _myWorkflow.Retry();
            return true;
        }
        [HttpPost]
        public async Task<bool> Terminate()
        {
            _logger.LogInformation("Terminate...");
            await _myWorkflow.Terminate();
            return true;
        }
    }
}
